/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ttt.nor2.main;

import com.ttt.nor2.config.CfgAlarm;
import com.ttt.nor2.db.ALarmFromExchange;
import com.ttt.nor2.db.DBMysql;
import com.ttt.nor2.db.HtbALarmDesc;
import com.ttt.nor2.thread.ThManageAlarm;
import com.ttt.nor2.util.ChkArgs;
import com.ttt.nor2.util.ExceptionUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

/**
 *
 * @author anuphabm
 */
public class MainManageALarm {

    private static Logger logger = Logger.getLogger(MainManageALarm.class);

    public static void main(String args[]) {

        ChkArgs chkargs = new ChkArgs(args);
        Properties prop = chkargs.getProps();
        PropertyConfigurator.configure(chkargs.getFileConfig());
        logger.info("Start Application Manage ALarm...");
        // get
        String url = prop.getProperty("URL");
        String usr = prop.getProperty("USER");
        String pwd = prop.getProperty("PWD");
        String db = prop.getProperty("DBNAME");
        String postUrl = prop.getProperty("POSTURL");
        String timeChkdup = prop.getProperty("TIME_CHKDUP");
        int sleep = Integer.parseInt(prop.getProperty("THRED_SLEEP"));
        int thWork = Integer.parseInt(prop.getProperty("MAX_THREAD"));
        //connection db
        Connection conn = DBMysql.dbConn(url, usr, pwd, db);
        logger.info("Connection db sussess...");
        // load data working for number alarm
        //System.exit(-1);
        while (true) {
            HtbALarmDesc ht = new HtbALarmDesc(conn);
            Hashtable htAlarm = ht.loadData();

            String sql = "select transid, alarm_num, ncen_code, ur_code, datetime_alarm, alarm_text, " +
                    "case event when 'DAL' then 'Start' when 'FAL' then 'Recovery' end as event " +
                    " from alarm_exchange where status ='N' and event in('DAL','FAL') " +
                    "order by stamptime limit " + thWork;
            logger.debug(sql);
            try {
                PreparedStatement pstmt = conn.prepareStatement(sql);
                ResultSet rs = pstmt.executeQuery();
                while (rs.next()) {

                    //check working thread
                    if (ThManageAlarm.getThWork() > thWork) {
                        thSleep(sleep);
                        continue;
                    }

                    ALarmFromExchange alarm = new ALarmFromExchange();
                    alarm.setTransid(rs.getString("transid"));
                    alarm.setAlarmNum(rs.getInt("alarm_num"));
                    alarm.setNcenCode(rs.getInt("ncen_code"));
                    alarm.setUrCode(rs.getString("ur_code"));
                    alarm.setTimeAlarm(rs.getString("datetime_alarm"));
                    alarm.setAlarm_prop(rs.getString("event"));
                    alarm.setAlarmExchange(rs.getString("alarm_text"));
                    logger.info(alarm.getTransid() + " alarm num[" + alarm.getAlarmNum() + "]");
                    logger.info(alarm.getTransid() + " ncec[" + alarm.getNcenCode() + "]");
                    logger.info(alarm.getTransid() + " urcode[" + alarm.getUrCode() + "]");
                    logger.info(alarm.getTransid() + " time[" + alarm.getTimeAlarm() + "]");
                    logger.info(alarm.getTransid() + " event[" + alarm.getAlarm_prop() + "]");
                    logger.info(alarm.getTransid() + " alarm[" + alarm.getAlarmExchange() + "]");
                    CfgAlarm cfg = new CfgAlarm();
                    cfg.setHashtable(htAlarm);
                    cfg.setConn(conn);
                    cfg.setPostUrl(postUrl);
                    cfg.setChkdup(timeChkdup);
                    //run thread
                    ThManageAlarm th = new ThManageAlarm(cfg, alarm);
                    th.start();

                }// end
                rs.close();
                pstmt.close();
                rs = null;
                pstmt = null;
            } catch (Exception e) {
                logger.error("Query load alarm exchange error! " + ExceptionUtil.getStackTrace(e));
                try {
                    conn.close();
                } catch (SQLException ex) {
                    logger.error("Close db error! " + ExceptionUtil.getStackTrace(ex));
                }
            } finally {
                // gabace collecter
                System.gc();
                // thread sleep
                thSleep(sleep);
            }

        }//end loop while never die

    }// end main

    private static void thSleep(int sleep) {
        try {
            Thread.sleep(sleep);
            logger.debug("Thread sleep [" + sleep + "]");
        } catch (Exception e) {
            logger.error("Exception Thread sleep " + ExceptionUtil.getStackTrace(e));
        }
    }
}
